import PageLayout from "@/components/PageLayout";
import {
  Button,
  Center,
  Flex,
  Group,
  Modal,
  Pagination,
  Paper,
  PasswordInput,
  Space,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import UserPill from "@/components/UserPill";
import When from "@/components/When";
import { useForm } from "@mantine/form";
import { IconPlus, IconSearch } from "@tabler/icons-react";
import { useParams } from "react-router-dom";
import { useImmer } from "use-immer";

import RenderIf from "@/components/RenderIf";
import dayjs from "dayjs";
import BusinessRoleRenderer from "./BusinessRoleRenderer";

export default function UserList() {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const { role } = useParams();

  const pageMeta = getPageMeta(role);

  const [pagingCondition, setPagingCondition] = useImmer({
    nickname: "",
    username: "",
    pageIndex: 0,
    pageSize: 10,
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      username: "",
      nickname: "",
      status: "",
    },
    validate: {},
  });

  const search = (values) => {
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const userQuery = tanstackQuery("/api/admin/users", {
    ...pagingCondition,
    role: role,
    pageNo: pagingCondition.pageIndex,
    pageSize: pagingCondition.pageSize,
  });

  const totalPages = userQuery.data?.totalPages;

  const rowRenderer =
    role === "PARTY_A" ? partyARowRenderer : businessRowRenderer;

  const rows = userQuery.data?.content.map(rowRenderer);

  return (
    <PageLayout title={pageMeta.title}>
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="space-between"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          {role === "PARTY_A" && (
            <RenderIf auth="PartyAUserManagement">
              <AddPartyAUserButton />
            </RenderIf>
          )}
          <Space />

          <Flex
            gap="md"
            justify="flex-end"
            align="flex-end"
            direction="row"
            wrap="wrap"
          >
            <TextInput
              description="用户名"
              clearable
              placeholder="精确匹配"
              {...searchForm.getInputProps("username")}
              w={200}
            />
            <TextInput
              description="昵称"
              clearable
              placeholder="模糊匹配"
              {...searchForm.getInputProps("nickname")}
              w={200}
            />
            <Button type="submit" rightSection={<IconSearch size={14} />}>
              搜索
            </Button>
          </Flex>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Paper p="md">
          <Table verticalSpacing={"sm"}>
            {role === "PARTY_A" ? <PartyAUserHeader /> : <BusinessUserHeader />}
            <Table.Tbody>{rows}</Table.Tbody>
          </Table>
        </Paper>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}

const businessRowRenderer = (user, index) => (
  <Table.Tr key={index}>
    <Table.Td>
      <Text>{index + 1}</Text>
    </Table.Td>
    <Table.Td>
      <UserPill user={user.user} />
    </Table.Td>
    <Table.Td>
      <BusinessRoleRenderer role={user.highestRole} />
    </Table.Td>
    <Table.Td>
      <Text>{user.user.mobile}</Text>
    </Table.Td>
    <Table.Td>
      <Text>{dayjs(user.user.createdAt).format("YYYY/MM/DD HH:mm:ss")}</Text>
    </Table.Td>

    <Table.Td>
      <Group>
        <Button
          variant="subtle"
          size="xs"
          onClick={() => window.open(`../users/${user.id}`, "_blank")}
        >
          详情
        </Button>
      </Group>
    </Table.Td>
  </Table.Tr>
);

const partyARowRenderer = (user, index) => (
  <Table.Tr key={index}>
    <Table.Td>
      <Text>{index + 1}</Text>
    </Table.Td>
    <Table.Td>
      <Text>{user.id}</Text>
    </Table.Td>
    <Table.Td>
      <UserPill user={user.user} />
    </Table.Td>
    <Table.Td>
      <Text>{dayjs(user.user.createdAt).format("YYYY/MM/DD HH:mm:ss")}</Text>
    </Table.Td>

    <Table.Td>
      <Group>
        <Button
          variant="subtle"
          size="xs"
          onClick={() => window.open(`../users/${user.id}`, "_blank")}
        >
          详情
        </Button>
      </Group>
    </Table.Td>
  </Table.Tr>
);

function BusinessUserHeader() {
  return (
    <Table.Thead>
      <Table.Tr>
        <Table.Th w={"3%"}></Table.Th>
        <Table.Th w={"20%"}>昵称</Table.Th>
        <Table.Th w={"8%"}>最高身份</Table.Th>
        <Table.Th w={"36%"}>电话</Table.Th>
        <Table.Th w={"20%"}>创建时间</Table.Th>
        <Table.Th>操作</Table.Th>
      </Table.Tr>
    </Table.Thead>
  );
}

function PartyAUserHeader() {
  return (
    <Table.Thead>
      <Table.Tr>
        <Table.Th w={"4%"}></Table.Th>
        <Table.Th w={"10%"}>ID</Table.Th>
        <Table.Th w={"60%"}>昵称</Table.Th>
        <Table.Th w={"20%"}>创建时间</Table.Th>
        <Table.Th>操作</Table.Th>
      </Table.Tr>
    </Table.Thead>
  );
}

function getPageMeta(role) {
  if (role === "AG_CSR") {
    return { title: "顾客管理" };
  }
  if (role === "AG_SHOP") {
    return { title: "店铺管理" };
  }
  if (role === "AG_WHS") {
    return { title: "批发商管理" };
  }
  if (role === "AG_AGENT") {
    return { title: "代理商管理" };
  }
  if (role === "MANAGER") {
    return { title: "业务经理管理" };
  }
  if (role === "AG_DIRECTOR") {
    return { title: "总监管理" };
  }
  if (role === "AU_DIRECTOR") {
    return { title: "董事管理" };
  }

  if (role === "PARTY_A") {
    return { title: "内部人员管理" };
  }
}

function AddPartyAUserButton() {
  const { tanstackInvalidate, restPOST } = useAPIUtils();
  const [opened, handlers] = useDisclosure(false);

  const form = useForm({
    mode: "uncontrolled",
    initialValues: {
      id: "",
      username: "",
      nickname: "",
      password: "",
    },

    validate: {
      id: (value) =>
        /^\d{5}$/.test(value) && value >= 10001 && value <= 19999
          ? null
          : "ID 必须是 10000 到 19999 之间的数字",
      username: (value) =>
        /^[A-Za-z0-9]+$/.test(value)
          ? null
          : "用户名只能包含大小写字母和数字，且不能包含空格",
      nickname: (value) =>
        /^[^\s]{1,20}$/.test(value)
          ? null
          : "昵称不能为空且不能包含空格，且最长为 20 个字符",
      password: (value) =>
        /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(value)
          ? null
          : "密码必须至少包含 8 个字符，并同时包含字母和数字",
    },
  });

  const addPartyAUser = async (values) => {
    if (values.password !== values.passwordConfirm) {
      notifications.show({
        title: "两次输入的密码不一致",
        color: "red",
      });
      return;
    }

    await restPOST(`/api/admin/users/partyA`, values);
    closeModal();
  };

  const closeModal = () => {
    handlers.close();
    tanstackInvalidate("/api/admin/users");
    form.reset();
  };

  return (
    <>
      <Button
        variant="light"
        aria-label="add"
        rightSection={<IconPlus size={14} />}
        onClick={handlers.toggle}
      >
        添加
      </Button>
      <Modal
        opened={opened}
        onClose={closeModal}
        title="添加内部人员"
        centered
        size={800}
      >
        <form onSubmit={form.onSubmit(addPartyAUser)}>
          <TextInput
            label="ID"
            withAsterisk
            placeholder="请输入 10000 到 19999 之间的数字"
            {...form.getInputProps("id")}
            required
          />

          <TextInput
            label="用户名"
            withAsterisk
            placeholder="用户名只能包含大小写字母和数字，且不能包含空格"
            {...form.getInputProps("username")}
            required
          />

          <TextInput
            label="昵称"
            withAsterisk
            placeholder="昵称不能为空且不能包含空格，且最长为 20 个字符"
            {...form.getInputProps("nickname")}
            required
          />

          <PasswordInput
            withAsterisk
            label="密码"
            placeholder="密码必须至少包含 8 个字符，并同时包含字母和数字"
            {...form.getInputProps("password")}
            required
          />
          <PasswordInput
            withAsterisk
            label="重复密码"
            placeholder="密码必须至少包含 8 个字符，并同时包含字母和数字"
            {...form.getInputProps("passwordConfirm")}
            required
          />
          <Group justify="flex-end" mt="md">
            <Button type="submit">提交</Button>
          </Group>
        </form>
      </Modal>
    </>
  );
}
